package com.vr.xuecheng.content.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vr.xuecheng.base.dto.BasePageParamsDTO;
import com.vr.xuecheng.base.exception.XueChengPlusException;
import com.vr.xuecheng.base.response.PageResult;
import com.vr.xuecheng.common.util.SecurityUtils;
import com.vr.xuecheng.content.mapper.CourseBaseMapper;
import com.vr.xuecheng.content.model.dto.CourseAddOrUpdateParamsDTO;
import com.vr.xuecheng.content.model.dto.QueryCourseParamsDTO;
import com.vr.xuecheng.content.model.entity.CourseBase;
import com.vr.xuecheng.content.model.entity.CourseCategory;
import com.vr.xuecheng.content.model.entity.CourseMarket;
import com.vr.xuecheng.content.model.vo.AddOrUpdateCourseResponseVO;
import com.vr.xuecheng.content.model.vo.CourseBaseOfPreviewVO;
import com.vr.xuecheng.content.model.vo.CourseBasePageVO;
import com.vr.xuecheng.content.model.vo.CourseBaseVO;
import com.vr.xuecheng.content.service.ICourseBaseService;
import com.vr.xuecheng.content.service.ICourseCategoryService;
import com.vr.xuecheng.content.service.ICourseMarketService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;


/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author hsh
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements ICourseBaseService {
    private final CourseBaseMapper courseBaseMapper;
    private final ICourseMarketService courseMarketService;
    private final ICourseCategoryService courseCategoryService;
//    private final ITeachplanService teachPlanService;

    @Override
    public PageResult<CourseBasePageVO> page(BasePageParamsDTO basePageParamsDTO, QueryCourseParamsDTO queryCourseParamsDTO) {
        // 获取当前用户信息
        SecurityUtils.User user = SecurityUtils.getUser();
        // 1、开启分页查询
        Page<CourseBase> page = new Page<>(basePageParamsDTO.getPageNo(), basePageParamsDTO.getPageSize());

        // 2、分页条件查询
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, new LambdaQueryWrapper<CourseBase>()
                .func(queryCourseParamsDTO != null, courseBaseLambdaQueryWrapper -> courseBaseLambdaQueryWrapper
                        .eq(!StrUtil.isBlank(queryCourseParamsDTO.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDTO.getAuditStatus())
                        .like(!StrUtil.isBlank(queryCourseParamsDTO.getCourseName()), CourseBase::getName, queryCourseParamsDTO.getCourseName())
                        .eq(!StrUtil.isBlank(queryCourseParamsDTO.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDTO.getPublishStatus()))
                        .eq(CourseBase::getCompanyId, user.getCompanyId())
        );

        // 3、拷贝数据
        List<CourseBase> records = pageResult.getRecords();
        List<CourseBasePageVO> courseBasePageVOList = BeanUtil.copyToList(records, CourseBasePageVO.class);
        // 4、TODO 根据课程id映射对应的课程其他信息
        List<Long> courseIds = courseBasePageVOList.stream().map(CourseBasePageVO::getId).toList();
        return new PageResult<>(courseBasePageVOList, pageResult.getTotal(), pageResult.getCurrent(), pageResult.getSize());
    }

    @Override
    public CourseBaseVO getCourseBaseById(Long id) {
        // 1、根据id查询课程基本信息
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if (courseBase == null) {
            return new CourseBaseVO();
        }
        // 2、拷贝数据
        CourseBaseVO courseBaseVO = BeanUtil.toBean(courseBase, CourseBaseVO.class);
        // 3、通过id获取到关联的其他数据
        CourseMarket courseMarket = courseMarketService.lambdaQuery().eq(CourseMarket::getId, id).one();
        if (courseMarket != null) {
            courseBaseVO
                    .setCharge(courseMarket.getCharge())
                    .setQq(courseMarket.getQq())
                    .setWechat(courseMarket.getWechat())
                    .setPhone(courseMarket.getPhone())
                    .setPrice(courseMarket.getPrice())
                    .setOriginalPrice(courseMarket.getOriginalPrice())
                    .setValidDays(courseMarket.getValidDays());
        }
        return courseBaseVO;
    }

    @Override
    @Transactional
    public AddOrUpdateCourseResponseVO add(CourseAddOrUpdateParamsDTO courseAddOrUpdateParamsDTO) {
        if (courseAddOrUpdateParamsDTO == null) {
            throw new IllegalArgumentException("课程信息为空");
        }
        // 1、新增课程基本信息
        CourseBase courseBase = BeanUtil.toBean(courseAddOrUpdateParamsDTO, CourseBase.class);

        // 课程状态为未提交
        courseBase.setAuditStatus("202002");
        // 课程发布状态未发布
        courseBase.setStatus("203001");
        // TODO 公司id，待改
        courseBase.setCompanyId(1232141425L);
        // TODO 获取当前登录用户信息,待改
        courseBase.setCreatePeople("48");
        courseBase.setChangePeople("48");

        if ("201001".equals(courseAddOrUpdateParamsDTO.getCharge())) {
            if (courseAddOrUpdateParamsDTO.getPrice() == null || courseAddOrUpdateParamsDTO.getPrice().compareTo(BigDecimal.ZERO) <= 0 || courseAddOrUpdateParamsDTO.getOriginalPrice() == null || courseAddOrUpdateParamsDTO.getOriginalPrice().compareTo(BigDecimal.ZERO) <= 0) {
                // 表示收费状态价格有问题
                XueChengPlusException.cast("课程收费时价格必须大于0");
            }
        }
        courseBaseMapper.insert(courseBase);
        // 2、新增课程关联的营销信息
        CourseMarket newCourseMarket = courseMarketService.saveCourseMarket(courseAddOrUpdateParamsDTO, courseBase);
        // 3、构建返回结果
        return this.buildResult(courseAddOrUpdateParamsDTO, courseBase, newCourseMarket);
    }

    private AddOrUpdateCourseResponseVO buildResult(CourseAddOrUpdateParamsDTO courseAddOrUpdateParamsDTO, CourseBase courseBase, CourseMarket newCourseMarket) {
        AddOrUpdateCourseResponseVO addOrUpdateCourseResponseVO = BeanUtil.toBean(courseBase, AddOrUpdateCourseResponseVO.class);
        BeanUtil.copyProperties(newCourseMarket, addOrUpdateCourseResponseVO);
        // 查询课程关联的分类信息
        List<CourseCategory> categoryList = courseCategoryService.lambdaQuery()
                .func(courseAddOrUpdateParamsDTO != null, courseCategoryLambdaQueryWrapper -> {
                            courseCategoryLambdaQueryWrapper
                                    .eq(courseAddOrUpdateParamsDTO.getMt() != null, CourseCategory::getId, courseAddOrUpdateParamsDTO.getMt())
                                    .or()
                                    .eq(courseAddOrUpdateParamsDTO.getSt() != null, CourseCategory::getId, courseAddOrUpdateParamsDTO.getSt());
                        }
                ).list();
        if (!categoryList.isEmpty()) {
            addOrUpdateCourseResponseVO
                    .setMtName(categoryList.get(0).getName())
                    .setStName(categoryList.get(1).getName());
        }

        return addOrUpdateCourseResponseVO;
    }

    @Override
    @Transactional
    public AddOrUpdateCourseResponseVO updateCourseBase(CourseAddOrUpdateParamsDTO courseAddOrUpdateParamsDTO) {
        if (courseAddOrUpdateParamsDTO == null || courseAddOrUpdateParamsDTO.getId() == null) {
            XueChengPlusException.cast("更新信息不能为空");
        }
        // 1、更新课程基本信息
        // 先查询课程基本信息
        CourseBase courseBase = courseBaseMapper.selectById(courseAddOrUpdateParamsDTO.getId());
        if (courseBase == null) {
            XueChengPlusException.cast("课程信息不存在");
        }
        BeanUtil.copyProperties(courseAddOrUpdateParamsDTO, courseBase);

        if ("201001".equals(courseAddOrUpdateParamsDTO.getCharge())) {
            if (courseAddOrUpdateParamsDTO.getPrice() == null || courseAddOrUpdateParamsDTO.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
                // 表示收费状态价格有问题
                XueChengPlusException.cast("课程收费时价格必须大于0");
            }
        }

        courseBaseMapper.updateById(courseBase);
        // 2、更新课程营销信息
        CourseMarket courseMarket = courseMarketService.saveCourseMarket(courseAddOrUpdateParamsDTO, courseBase);
        // 变成未提交
        courseBase.setAuditStatus("202001");
        return this.buildResult(courseAddOrUpdateParamsDTO, courseBase, courseMarket);
    }

    @Override
    public CourseBaseOfPreviewVO getCourseBaseInfoById(Long courseId) {
        if (courseId == null) {
            XueChengPlusException.cast("课程id为空");
        }
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            return null;
        }
        // 查询关联的分类信息
        List<CourseCategory> categoryList = courseCategoryService.lambdaQuery()
                .func(courseCategoryLambdaQueryWrapper -> {
                    courseCategoryLambdaQueryWrapper
                            .eq(courseBase.getMt() != null, CourseCategory::getId, courseBase.getMt())
                            .or()
                            .eq(courseBase.getSt() != null, CourseCategory::getId, courseBase.getSt());
                }).list();
        // 查询关联的营销信息
        CourseMarket courseMarket = courseMarketService.lambdaQuery()
                .eq(CourseMarket::getId, courseId)
                .one();
        // 封装数据
        CourseBaseOfPreviewVO courseBaseOfPreviewVO = BeanUtil.toBean(courseBase, CourseBaseOfPreviewVO.class);
        if (!categoryList.isEmpty()) {
            courseBaseOfPreviewVO.setMtName(categoryList.get(0).getName());
            courseBaseOfPreviewVO.setStName(categoryList.get(1).getName());
        }
        if (courseMarket != null) {
            BeanUtil.copyProperties(courseMarket, courseBaseOfPreviewVO);
        }
        return courseBaseOfPreviewVO;
    }


}
